package cn.lytcom.architecture;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.facebook.stetho.Stetho;
import com.squareup.leakcanary.LeakCanary;

import org.greenrobot.greendao.identityscope.IdentityScopeType;

import cn.lytcom.architecture.model.DaoMaster;
import cn.lytcom.architecture.model.DaoSession;
import timber.log.Timber;

/**
 * Created by lytcom on 2017/4/23.
 */

public class MyApplication extends Application {

    private static final String DB_NAME = "app_db";
    private static MyApplication myApplication;
    private AppComponent appComponent;
    private DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
        setupGreenDao();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
            Stetho.initializeWithDefaults(this);
            if (LeakCanary.isInAnalyzerProcess(this)) {
                // This process is dedicated to LeakCanary for heap analysis.
                // You should not init your app in this process.
                return;
            }
            LeakCanary.install(this);
        }
    }

    private void setupGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, DB_NAME);
        SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
        daoSession = new DaoMaster(sqLiteDatabase).newSession(IdentityScopeType.None);
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    public static Context getAppContext() {
        return myApplication.getApplicationContext();
    }

    public static MyApplication getMyApplication() {
        return myApplication;
    }

    public static AppComponent getAppComponent() {
        return myApplication.appComponent;
    }
}
